package com.sky.service.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Transactional //开启事务（涉及多表操作）
    public void addDish(DishDTO dto) {
        //1.菜品基本信息数据存入dish表
        Dish dish=new Dish();
        BeanUtils.copyProperties(dto,dish);
        dishMapper.insert(dish);
        //2.构造菜品口味列表数据
        Long dishId = dish.getId();
       List<DishFlavor> dishFlavorList=dto.getFlavors();
        //关联菜品id
        if (dishFlavorList != null && dishFlavorList.size() > 0) {
            dishFlavorList.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });
            //向口味表插入n条数据
            dishFlavorMapper.insertBatch(dishFlavorList);
        }

    }

    /**
     * 分页查询
     * @param dto
     * @return
     */

    @Override
    public PageResult page(DishPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        Page<DishVO> page =dishMapper.list(dto);

        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 删除菜品
     * @param ids
     */
    @Transactional  //开启事务
    public void delete(List<Long> ids) {
       ids.forEach(id->{
           Dish dish=dishMapper.selectById(id);
           if (dish.getStatus() == StatusConstant.ENABLE){
               throw  new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
           }
       });

        Integer count=  setmealMapper.countByDishId(ids);
       if (count>0){
           throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
       }
       dishMapper.deleteBatch(ids);
       dishFlavorMapper.deleteBatch(ids);
    }

    @Override
    public DishVO getById(Long id) {
        DishVO dishVO=new DishVO();
        //根据菜品id查询菜品信息
        Dish dish=dishMapper.selectById(id);
        BeanUtils.copyProperties(dish,dishVO);

        //根据菜品id的查询口味，封装到vo中
       List<DishFlavor> flavors= dishFlavorMapper.selectByDishId(id);
        dishVO.setFlavors(flavors);

        //vo对象返回
        return dishVO;
    }

    @Transactional
    public void update(DishDTO dto) {
        Dish dish=new Dish();
        BeanUtils.copyProperties(dto,dish);
        //修改菜品信息
        dishMapper.update(dish);
        //修改口味信息
        dishFlavorMapper.deleteDishId(dto.getId());

        List<DishFlavor> flavors=dto.getFlavors();
        if (flavors !=null && flavors.size()>0){
            flavors.forEach(flavor ->{
                flavor.setDishId(dto.getId());
            });
            dishFlavorMapper.insertBatch(flavors);
        }

    }

    @Transactional
    public void start(Integer status, Long id) {
    Dish dish=new Dish();
    dish.setId(id);
    dish.setStatus(status);
    dishMapper.update(dish);
        if (status == StatusConstant.DISABLE) {
            // 如果是停售操作，还需要将包含当前菜品的套餐也停售
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(id);
            List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(dishIds);
            if (setmealIds != null && setmealIds.size() > 0) {
                for (Long setmealId : setmealIds) {
                    Setmeal setmeal = Setmeal.builder()
                            .id(setmealId)
                            .status(StatusConstant.DISABLE)
                            .build();
                    setmealMapper.update(setmeal);
                }
            }
        }
    }

    @Override
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.listId(dish);
    }

    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.listId(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
